package com.sjc.designpattern.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname FlyweightPatternDemo
 * @Description 享元模式：享受元数据，简单的jvm内存对象池 缓存
 * flyweight模式场景
 * 1. 现在需要缓存一些数据，比如说权限，根据权限的ID作为key，权限数据自己本身是value
 * 2. 不需要使用复杂的ehcache框架之类的，特别特别的简单的
 * 3. 基于自己的Map去实现一套东西
 * @Date 2020/4/26 11:46
 * @Created by SangJiacun
 */
public class FlyweightPatternDemo {
    public static void main(String[] args) {
        Flyweight flyweight = FlyweightFactory.get("对象1");
        flyweight.execute();

        Flyweight flyweight1 = FlyweightFactory.get("对象1");
        flyweight1.execute();

        System.out.println(flyweight == flyweight1);

        // 享元
        // 享受，元数据
        // 同一个数据，我就认为是一个元数据，整个系统里这个数据就一份，缓存起来
        // 整个系统对这个数据，全部享受他一个对象实例即可

        // 直接既有内存来缓存一块数据，用享元模式
    }

    public interface Flyweight{
        void execute();
        String getName();
        void setName(String name);
    }

    public static class ConcreteFlyweight implements Flyweight{

        private String name;

        public ConcreteFlyweight(String name) {
            this.name = name;
        }

        @Override
        public void execute() {
            System.out.println(name + "执行功能逻辑");
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public void setName(String name) {
            this.name = name;
        }
    }

    public static class FlyweightFactory{
        private static Map<String,Flyweight> cachePool = new HashMap<String ,Flyweight>();

        public static Flyweight get(String name){
            Flyweight flyweight = cachePool.get(name);
            if(null == flyweight){
                flyweight = new ConcreteFlyweight(name);
                cachePool.put(name,flyweight);
            }
            return flyweight;
        }
    }

}
